import { Conversion } from "./method";
import { Component } from "../component/menu";
import { Api } from "./api";
import { Socket } from './socket';
import { Methods,baseEmit } from './method';

//单击导航栏
let nav = document.querySelectorAll(".head-nav a"),
    selectNav = nav[0];

nav.forEach((value,index,array)=>{
    value.onclick = ()=>{
        if(selectNav){
            selectNav.style.background = "#0661bd";
        }
        switch (value.innerText){
            case "首页":
                window.location.href = `./index.html`;
                break;
        }
        value.style.background = "#061dbd";
        selectNav = value;
    }
});
//单击导航栏end

let userSelect = document.querySelectorAll('.user-select');
userSelect.forEach((value,index,array)=>{
    value.onclick = ($event)=>{
        let name = Conversion.loginEnglish(event.toElement.innerText);
        window.location.href = `./html/login.html?${name}`;
    };
});

let socket = new Socket();


socket.Echo().then((res)=>{
    document.querySelector(".content").innerHTML = Component.homeEntryBox()+'<p class="content-title">最新动态</p>'+Component.menu(res);
}).then(()=>{
    let base;
    //单击写文章
    document.querySelector(".HomeEntry-ask").onclick = ()=>{
        Component.write().then((res)=>{
            document.querySelector(".content").innerHTML = res
        }).then(()=>{
            //上传图片
            let input = document.getElementById("file_input");
            let methods = new Methods();
            methods.loadImg(input);
            baseEmit.subscribe((res)=>{
                base = res;
            });
        }).then(()=>{
            //单击发布
            document.querySelector(".write-publish").onclick = ()=>{
                let title = document.querySelector(".input-title").value,
                    content = document.querySelector(".content-publish").value;
                let cookies=document.cookie.split("; "),token = "";
                cookies.forEach((value,index,array)=>{
                    if(value.split("=")[0] === "web"){
                        token = value.split("=")[1]
                    }
                });
                if (title && content) {
                    console.log(base);
                    Api.postHttp("publish", {"title": title, "content": content,"images":JSON.stringify(base)},token).then(res => {
                        window.location.href = `./index.html`;
                    }).catch(res=>{
                        window.location.href = `./index.html`;
                    })
                } else {
                    alert("请输入完整的信息！")
                }
            }
        });
    };
});







